<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryForm" size="small" :rules="rules" :inline="true" v-show="showSearch"
            label-width="150px">
            <el-form-item :label="$t('parameter.settings.deviceTypeId')" prop="deviceTypeId">
                <el-select v-model="queryParams.deviceTypeId" clearable @change="deviceTypeChange">
                    <el-option v-for="dict in deviceTypeOptions" :key="dict.value" :label="dict.label"
                        :value="dict.value" />
                </el-select>
            </el-form-item>
            <el-form-item :label="$t('parameter.settings.deviceModelId')" prop="deviceModelId">
                <el-select v-model="queryParams.deviceModelId" clearable>
                    <el-option v-for="dict in deviceModelOptions" :key="dict.value" :label="dict.label"
                        :value="dict.value" />
                </el-select>
            </el-form-item>
            <el-form-item :label="$t('parameter.settings.deviceCode')" prop="deviceCode">
                <el-autocomplete v-model.trim="queryParams.deviceCode" placeholder="输入设备IMEI后四位快速匹配" class="inline-input"
                    :fetch-suggestions="queryDevice" :trigger-on-focus="false" style="width: 220px;" :maxlength="80"
                    size="small">
                </el-autocomplete>
            </el-form-item>

            <el-form-item :label="$t('parameter.query.information')" class='paramName_item' prop="params">
                <el-badge :value="checkedNums" class="item" size="small" style="width: 195px">
                    <el-button @click='handleSelectNames' size="small" style="width: 200px">{{$t('parameter.query.parameter')}}</el-button>
                </el-badge>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery"
                    v-hasPermi="['param:device:set']">{{$t('parameter.query.realTime')}}</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
                    v-hasPermi="['system:argument:resh']">{{ $t('common.button.reset')}}</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleRealQuery"
                    v-hasPermi="['param:device:set']">{{ $t('parameter.query.historical')}}</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
                    v-hasPermi="['system:argument:derive']">{{ $t('common.button.export') }}</el-button>
            </el-col>
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" border :data="versionList" :empty-text="$t('parameter.query.data')">
            <el-table-column :show-overflow-tooltip="true" property="deviceCode" :label="$t('parameter.settings.deviceCode')" />
            <el-table-column :show-overflow-tooltip="true" property="paramComment" :label="$t('parameter.query.paramComment')" />
            <el-table-column :show-overflow-tooltip="true" property="paramName" :label="$t('parameter.query.parameterName')" />
            <el-table-column :show-overflow-tooltip="true" property="paramValue" :label="$t('parameter.query.parameterValue')" />
            <el-table-column :label="$t('parameter.query.updateTime')" align="center" prop="updateTime" width="180">
              <template #default="scope">
                <span>{{ parseTime(scope.row.updateTime) }}</span>
              </template>
            </el-table-column>
        </el-table>


        <el-dialog title="参数选择" :visible.sync="dialogVisible" width="30%">
            <div>
                <el-checkbox class='mb10' :indeterminate="isIndeterminate" v-model="checkAll"
                    @change="handleCheckAllChange">{{$t('parameter.query.all')}}</el-checkbox>
                <el-checkbox-group v-loading='checkedLoading' v-model="checkedNames" @change="handleCheckedNamesChange">
                    <el-checkbox v-for="item in paramNames" :label="item.value" :key="item.value">{{
                        item.label }}</el-checkbox>
                </el-checkbox-group>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">{{ $t('common.dialog.cancel') }}</el-button>
                <el-button type="primary" @click="handleConfirm">{{
                    $t('common.dialog.confirm') }}</el-button>
            </span>
        </el-dialog>

    </div>
</template>
<script>
import { typeTree } from "@/api/device/type";
import { modelTree } from "@/api/device/model";
import {queryDeviceIdAsync} from '@/api/query/device';
import { commandParamsList, deviceParamList } from "@/api/argument/query/data";
import { listCommandParams, getCommandParams, delCommandParams, addCommandParams, updateCommandParams } from "@/api/parameter/item/data";

export default {
    name: "Version",
    data() {
        return {
            deviceModelOptions: [],
            deviceTypeOptions: [],
            source: null,
            dialogVisible: false,
            paramNames: [],
            checkedNames: [],
            checkedLoading: false,
            checkAll: false,
            isIndeterminate: false,
            checkedNums: 0,
            // 按钮loading
            buttonLoading: false,
            // 遮罩层
            loading: false,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 表格数据
            versionList: [],
            // 弹出层标题
            title: "",
            // 是否显示弹出层
            open: false,
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                deviceCode: undefined,
                isReal: 1, //1:历史同步数据，2：实时查询
                deviceTypeId: undefined,
                deviceModelId: undefined,
                params: [],
            },
            // 表单参数
            form: {},
            // 表单校验
            rules: {
                deviceCode: [{
                    required: true, message: this.$t('parameter.query.placeholder.imei'), trigger: 'blur'
                }],
                deviceTypeId: [{
                    required: true, message: this.$t('parameter.query.placeholder.type'), trigger: 'change'
                }],
                deviceModelId: [{
                    required: true, message: this.$t('parameter.query.placeholder.model'), trigger: 'change'
                }],
                params: [{
                    required: true, message: this.$t('parameter.query.placeholder.param'), trigger: 'change'
                }],
            }
        };
    },
    created() {
        // this.getList();
        this.getTypeTree();
    },
    methods: {
        getList() {
            this.$refs.queryForm.validate(valid => {
                if (valid) {
                    this.loading = true;
                    deviceParamList(this.queryParams).then(response => {
                        this.versionList = response.data;
                        this.total = response.total;
                        this.loading = false;
                    }).catch(response => {
                        this.loading = false;
                    });
                }
            })

        },
        getTypeTree() {
            typeTree().then(response => {
                this.deviceTypeOptions = response.data;
            });
        },
        deviceTypeChange(typeId) {
            if (typeId) {
                this.getModelTree(typeId)
            } else {
                this.uploadForm.deviceModelId = undefined
                this.deviceModelOptions = []
            }
        },
        getModelTree(typeId) {
            modelTree(typeId).then(response => {
                this.deviceModelOptions = response.data;
            });
        },
        // 取消按钮
        cancel() {
            this.open = false;
            this.reset();
        },
        // 表单重置
        reset() {
            this.form = {
                id: undefined,
                deviceType: undefined,
                deviceModel: undefined,
                params: [],
            };
            this.resetForm("form");
        },
        /** 获取实体参数数据接口 */
        handleQuery() {
            this.queryParams.isReal = 2;
            this.getList();
        },
        handleRealQuery() {
            this.queryParams.isReal = 1;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.resetForm("queryForm");
            // this.handleQuery();
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map(item => item.id)
            this.single = selection.length !== 1
            this.multiple = !selection.length
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.reset();
            this.open = true;
            this.title = "添加app版本管理";
        },
        /** 修改按钮操作 */
        handleUpdate(row) {
            this.loading = true;
            this.reset();
            const id = row.id || this.ids
            getVersion(id).then(response => {
                this.loading = false;
                this.form = response.data;
                this.open = true;
                this.title = "修改app版本管理";
            });
        },
        /** 提交按钮 */
        submitForm() {
            this.$refs["form"].validate(valid => {
                if (valid) {
                    this.buttonLoading = true;
                    if (this.form.id != null) {
                        updateVersion(this.form).then(response => {
                            this.$modal.msgSuccess("修改成功");
                            this.open = false;
                            this.getList();
                        }).finally(() => {
                            this.buttonLoading = false;
                        });
                    } else {
                        addVersion(this.form).then(response => {
                            this.$modal.msgSuccess("新增成功");
                            this.open = false;
                            this.getList();
                        }).finally(() => {
                            this.buttonLoading = false;
                        });
                    }
                }
            });
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            const ids = row.id || this.ids;
            this.$modal.confirm('是否确认删除app版本管理编号为"' + ids + '"的数据项？').then(() => {
                this.loading = true;
                return delVersion(ids);
            }).then(() => {
                this.loading = false;
                this.getList();
                this.$modal.msgSuccess("删除成功");
            }).catch(() => {
            }).finally(() => {
                this.loading = false;
            });
        },
        /** 导出按钮操作 */
        handleExport() {
            this.download('parameter/delivery/export', {
                ...this.queryParams
            }, `export_${new Date().getTime()}.xlsx`)
        },

        queryDevice(suffix, cb) {
            let from = { deviceId: suffix, source: this.source }
            queryDeviceIdAsync(from, cb)
        },

        handleSelectNames() {
            if (!this.queryParams.deviceTypeId || !this.queryParams.deviceModelId) {
                this.$message.error("请先选择设备信息");
                return;
            }
            !this.paramNames.length && this.getParamsList();
            this.dialogVisible = true;
        },

        handleCheckAllChange(val) {
            this.checkedNames = val ? this.paramNames.map(item => { return item.value }) : [];
            this.isIndeterminate = false;
        },
        handleCheckedNamesChange(val) {
            let checkedCount = val.length;
            this.isIndeterminate = checkedCount > 0 && checkedCount < this.paramNames.length;
        },
        handleConfirm() {
            this.dialogVisible = false;
            this.checkedNums = this.checkedNames.length;
            this.queryParams.params = this.checkedNames.map(item => {
                return { type: item }
            });
        },

        getParamsList() {
            const params = {
                deviceType: this.queryParams.deviceType,
                deviceModel: this.queryParams.deviceModel,
                commandType: 1,//1车辆设置,2参数查询,3参数下发
            }
            this.checkedLoading = true;
            listCommandParams(params).then(res => {
                if (res.code == 200) {
                    this.paramNames = res.rows.map(item => {
                        return {
                            label: item.paramLabel,
                            value: item.paramValue
                        }
                    })
                    this.checkedLoading = false;
                } else {
                    this.checkedLoading = false
                }

            })

        }
    }
};
</script>
<style lang='scss'>
.paramName_item {
    .el-form-item__label::before {
        content: "*";
        color: #ff4949;
        margin-right: 4px;
    }
}
</style>
